package com.example.project7.database;

import android.content.Context;
import android.content.SharedPreferences;
import com.example.project7.model.Book;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BookDatabase {
    private static final String PREF_NAME = "book_data";
    private static final String KEY_BOOKS = "books";
    private SharedPreferences sharedPreferences;
    private Gson gson;

    public BookDatabase(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
    }

    /**
     * 添加书籍
     * @param book 书籍对象
     */
    public void addBook(Book book) {
        List<Book> books = getAllBooks();
        // 生成唯一ID
        if (book.getId() == null || book.getId().isEmpty()) {
            book.setId(UUID.randomUUID().toString());
        }
        books.add(book);
        saveBooks(books);
    }

    /**
     * 更新书籍
     * @param book 书籍对象
     */
    public void updateBook(Book book) {
        List<Book> books = getAllBooks();
        for (int i = 0; i < books.size(); i++) {
            if (books.get(i).getId().equals(book.getId())) {
                books.set(i, book);
                break;
            }
        }
        saveBooks(books);
    }

    /**
     * 删除书籍
     * @param book 书籍对象
     */
    public void deleteBook(Book book) {
        List<Book> books = getAllBooks();
        books.remove(book);
        saveBooks(books);
    }

    /**
     * 根据用户邮箱获取书籍列表
     * @param userEmail 用户邮箱
     * @return 该用户的书籍列表
     */
    public List<Book> getBooksByUser(String userEmail) {
        List<Book> allBooks = getAllBooks();
        List<Book> userBooks = new ArrayList<>();
        for (Book book : allBooks) {
            if (book.getUserEmail() != null && book.getUserEmail().equals(userEmail)) {
                userBooks.add(book);
            }
        }
        return userBooks;
    }

    /**
     * 根据用户邮箱和查询条件搜索书籍
     * @param userEmail 用户邮箱
     * @param query 查询条件（书号或书名）
     * @return 匹配的书籍列表
     */
    public List<Book> searchBooks(String userEmail, String query) {
        List<Book> userBooks = getBooksByUser(userEmail);
        if (query == null || query.trim().isEmpty()) {
            return userBooks; // 空查询返回全部
        }
        
        List<Book> result = new ArrayList<>();
        String lowerCaseQuery = query.toLowerCase().trim();
        for (Book book : userBooks) {
            if ((book.getBookNumber() != null && book.getBookNumber().toLowerCase().contains(lowerCaseQuery)) ||
                (book.getBookName() != null && book.getBookName().toLowerCase().contains(lowerCaseQuery))) {
                result.add(book);
            }
        }
        return result;
    }

    /**
     * 获取所有书籍
     * @return 所有书籍列表
     */
    private List<Book> getAllBooks() {
        String json = sharedPreferences.getString(KEY_BOOKS, "");
        if (json.isEmpty()) {
            return new ArrayList<>();
        }
        
        Type type = new TypeToken<List<Book>>(){}.getType();
        return gson.fromJson(json, type);
    }

    /**
     * 保存书籍列表
     * @param books 书籍列表
     */
    private void saveBooks(List<Book> books) {
        String json = gson.toJson(books);
        sharedPreferences.edit().putString(KEY_BOOKS, json).apply();
    }
}